layui.define('element', function (exports) {
	"use strict";
	
	var TabMenu = function (filter, options) {
		this.options = options;
		this.tabMenu = options.tabMenu;
		this.filter = filter;
		this.element = layui.element;
		this.tabMenu = '<div class="layui-tab-menu">' + '<ul>'
			+ '<li lay-value="flush"><a>刷新</a></li>'
			+ '<li lay-value="current"><a>关闭当前页</a></li>'
			+ '<li lay-value="other"><a>关闭其他页</a></li>'
			+ '<li lay-value="all"><a>全部关闭</a></li>' + '</ul>' + '</div>';
	}

	TabMenu.prototype.init = function () {
		var that = this;
		if (that.tabMenu) {
			$("#" + that.filter).find('li').each(function () {
				var li = $(this);
				that.initContextMenu(li);
			});
		}
		that.unClose();
	}
	
	TabMenu.prototype.unClose = function(){
		var that = this;
		$("#" + that.filter).find('li').each(function () {
			var li = $(this);
			if(li.hasClass("lay-tab-unclose")){
				li.children(".layui-tab-close").hide();
			}
		});
	}

	TabMenu.prototype.initContextMenu = function (elem) {
		var that = this;
		elem.off("contextmenu").on(
			"contextmenu",
			function (e) {
				e.preventDefault();
				$(".layui-tab-menu").remove();
				$(document.body).append(that.tabMenu);
				var left = e.clientX;
				var top = e.clientY;
				$(".layui-tab-menu").css("left", left);
				$(".layui-tab-menu").css("top", top);

				if (elem.hasClass("lay-tab-unclose")) {
					$(".layui-tab-menu>ul>li[lay-value='current']")
						.addClass("layui-disabled");
				}

				$(document).click(function () {
					$(".layui-tab-menu").remove();
				});
				that.enentTabMenu(elem);
			});
	}

	TabMenu.prototype.enentTabMenu = function (elem) {
		var that = this;
		$(".layui-tab-menu ul").children("li").click(
			function () {
				if ($(this).hasClass("layui-disabled")) {
					return false;
				} else {
					var lay_value = $(this).attr("lay-value");
					var layid = elem.attr("lay-id");
					if (lay_value == 'flush') {
						var index = $(elem).index();
						var tar = $(".layui-tab-content>div").eq(index);
						var html = tar.html();
						tar.html(html);
					} else if (lay_value == 'current') {
						that.element.tabDelete(that.filter, layid);
					} else if (lay_value == 'other') {
						$('.layui-tab>ul>li').each(function (i, item) {
								var otherLayid = $(item).attr("lay-id");
								if (layid != otherLayid && !$(item).hasClass("lay-tab-unclose")) {
									that.element.tabDelete(that.filter,otherLayid);
								}
							});
					} else if (lay_value == 'all') {
						$('.layui-tab>ul>li').each(function (i, item) {
							var otherLayid = $(item).attr("lay-id");
							if (!$(item).hasClass("lay-tab-unclose")) {
								that.element.tabDelete(that.filter, otherLayid);
							}
						});
					}
				}
			});
	}

	exports('tabMenu', function (filter, options) {
		var tabMenu = new TabMenu(filter, options = options || {});
		tabMenu.init();
	});
});